from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
from enum import Enum
import time

# 数据模型
@dataclass
class OrderBook:
    asks: List[Tuple[float, float]]  # price, amount
    bids: List[Tuple[float, float]]
    timestamp: float

@dataclass
class Ticker:
    symbol: str
    last_price: float
    bid_price: float
    ask_price: float
    volume_24h: float
    timestamp: float

@dataclass
class Position:
    symbol: str
    size: float        # 持仓数量，正数为多头，负数为空头
    entry_price: float # 开仓均价
    leverage: float    # 杠杆倍数
    margin: float      # 保证金
    unrealized_pnl: float  # 未实现盈亏
    liquidation_price: float  # 强平价格
    timestamp: float

@dataclass
class Balance:
    asset: str
    free: float       # 可用余额
    locked: float     # 冻结余额
    total: float      # 总余额
    timestamp: float

class OrderStatus(Enum):
    PENDING = "pending"
    OPEN = "open"
    FILLED = "filled"
    CANCELED = "canceled"
    REJECTED = "rejected"
    EXPIRED = "expired"

class OrderSide(Enum):
    BUY = "buy"
    SELL = "sell"

class OrderType(Enum):
    MARKET = "market"
    LIMIT = "limit"

@dataclass
class Order:
    exchange_id: str   # 交易所ID
    order_id: str     # 订单ID
    symbol: str       # 交易对
    order_type: OrderType  # 订单类型
    side: OrderSide   # 买卖方向
    price: float      # 价格
    amount: float     # 数量
    filled: float     # 已成交数量
    status: OrderStatus  # 订单状态
    timestamp: float  # 创建时间

class BaseExchange(ABC):
    """交易所基类"""
    
    def __init__(self, api_key: str = "", api_secret: str = "", passphrase: str = ""):
        self.api_key = api_key
        self.api_secret = api_secret
        self.passphrase = passphrase
        self.name = ""  # 交易所名称

    @abstractmethod
    async def get_ticker(self, symbol: str) -> Ticker:
        """获取最新行情"""
        pass

    @abstractmethod
    async def get_orderbook(self, symbol: str, limit: int = 20) -> OrderBook:
        """获取订单簿"""
        pass

    @abstractmethod
    async def get_balance(self, asset: str = "") -> Dict[str, Balance]:
        """获取账户余额"""
        pass

    @abstractmethod
    async def get_positions(self, symbol: str = "") -> Dict[str, Position]:
        """获取持仓信息"""
        pass

    @abstractmethod
    async def create_order(self, symbol: str, order_type: OrderType, 
                          side: OrderSide, amount: float, price: float = 0) -> Order:
        """创建订单"""
        pass

    @abstractmethod
    async def cancel_order(self, symbol: str, order_id: str) -> bool:
        """取消订单"""
        pass

    @abstractmethod
    async def get_order(self, symbol: str, order_id: str) -> Order:
        """获取订单信息"""
        pass

    @abstractmethod
    async def get_open_orders(self, symbol: str = "") -> List[Order]:
        """获取未完成订单"""
        pass

    @abstractmethod
    async def create_market_order(self, symbol: str, side: OrderSide, amount: float) -> Order:
        """创建市价单"""
        pass
        
    @abstractmethod
    async def create_limit_order(self, symbol: str, side: OrderSide, 
                               price: float, amount: float) -> Order:
        """创建限价单"""
        pass
        
    @abstractmethod
    async def set_leverage(self, symbol: str, leverage: int) -> bool:
        """设置杠杆倍数"""
        pass
        
    @abstractmethod
    async def get_funding_rate(self, symbol: str) -> float:
        """获取资金费率"""
        pass
        
    @abstractmethod
    async def get_funding_time(self, symbol: str) -> int:
        """获取下次资金费时间"""
        pass 